package org.xiaojinlong.algo;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Jin Long
 * 2015/8/25
 */
public class ResizingArrayQueue<Item> implements Queue<Item> {
    private Item[] q = (Item[]) new Object[2]; // queue elements
    private int N; // number of elements on queue
    private int first; // index of first element of queue
    private int last; // index of next available slot

    @Override
    public boolean isEmpty() {
        return N == 0;
    }

    @Override
    public int size() {
        return N;
    }

    private void resize(int max) {
        assert max >= N;
        Item[] temp = (Item[]) new Object[max];
        for (int i = 0; i < N; i++)
            temp[i] = q[(first + i) % q.length];
        q = temp;
        first = 0;
        last = N;
    }

    @Override
    public void enqueue(Item item) {
        if (N == q.length) resize(2 * q.length);
        q[last++] = item;
        if (last == q.length) last = 0;
        N++;
    }

    @Override
    public Item dequeue() {
        if (isEmpty()) throw new NoSuchElementException("Queue underflow");
        Item item = q[first];
        q[first] = null;
        N--;
        first++;
        if(first == q.length) first = 0;
        if (N > 0 && N == q.length/4) resize(q.length / 2);
        return item;
    }

    @Override
    public Item peek() {
        if (isEmpty()) throw new NoSuchElementException("Queue underflow");
        return q[first];
    }

    @Override
    public Iterator<Item> iterator() {
        return new ArrayIterator();
    }

    private class ArrayIterator implements Iterator<Item> {
        private int i;

        @Override
        public boolean hasNext() {
            return i < N;
        }

        @Override
        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            Item item = q[(first + i) % q.length];
            i++;
            return item;
        }
    }
}
